import axios from 'axios'
import envFuncs from '@/config/base'
let env = envFuncs.getParams()
import store from '../../store'
import Q from 'q'

export const sourceOptions = {
  text: '客户来源',
  name: 'source_id',
  showSearch: true,
  class: 'txt-center',
  checked: '',
  value: 'source_id',
  options: []
}
export const secondSourceOptions = {
  text: '客户二级来源',
  name: 'second_source_id',
  parent: 'source_id',
  showSearch: true,
  class: 'txt-center',
  checked: '',
  value: 'second_source_id',
  options: []
}

export const getRemoteSourceOptions = (custom) => {
  const token = store.state.app.token
  const CRM_API_HOST = env.CRM_API_HOST
  axios.get(CRM_API_HOST + '/users/' + token + '/sources')
  .then((response) => {
    if (response.data.errcode === 0) {
      const sources = response.data.results
      const options = [{key: '不限', value: '-1'}]
      sources.forEach((source, index) => {
        options.push({key: source.source_name, value: source.id})
      })
      sourceOptions.options = options
    }
  })
}
export const getChildSourceOptions = (sourceId) => {
  const token = store.state.app.token
  const CRM_API_HOST = env.CRM_API_HOST
  const sourceOptions = [{key: '不限', value: '-1'}]
  secondSourceOptions.options = sourceOptions

  return Q.Promise((resolve) => {
    store.dispatch('getManagableChildSource', {id: sourceId})
    .then((response) => {
      console.log('response', response)
      if (response.errcode === 0) {
        const sources = response.results
        sources.forEach((source, index) => {
          sourceOptions.push({key: source.source_name, value: source.id, text: source.source_name})
        })
        secondSourceOptions.options = sourceOptions
        resolve(secondSourceOptions)
      } else {
        resolve(secondSourceOptions)
      }
    }).catch(() => {
      resolve({})
    })
  })
}


export const getSourceOptions = (sources) => {
  const options = [{text: '不限', value: '-1'}]
  for (const id in sources) {
    options.push({text: sources[id], value: id, options: getChildSourceOptions})
  }
  sourceOptions.options = options
  return sourceOptions
}
